<template>
  <el-card shadow="hover" style="margin-top:1rem;">
    <div slot="header" class="clearfix">
      <h3 style="float:left;">缺陷</h3>
      <span style="float:right;">
        <el-switch
          v-model="showDone"
          active-color="#67c23a"
          @change="handleChangeSwitch"
        />
        <span style="margin-left: 1rem;color: #909399;font-size: 14px;">总计: {{ total }} 条</span>
      </span>
    </div>
    <ListView :loading.sync="loading" :list-data="listData" @editUpdate="handleUpdate" @updateCheckboxApi="updateCheckboxApi" />

    <el-dialog :title="textMap[dialogStatus]" :visible.sync="dialogFormVisible" :close-on-click-modal="false" :width="'50vw'">
      <el-form ref="dataForm" :rules="rules" :inline="true" :model="temp" label-position="right" label-width="80px">
        <el-form-item label="名称" prop="name">
          <el-input v-model="temp.name" type="textarea" :autosize="{ minRows: 2, maxRows: 4}" placeholder="Tips：描述可以粘贴图片" style="width:calc(50vw - 140px)" />
        </el-form-item>
        <br>
        <el-form-item label="开始时间" prop="start_at">
          <el-date-picker v-model="temp.start_at" type="datetime" format="yyyy-MM-dd HH:mm" default-time="09:00:00" value-format="yyyy-MM-dd HH:mm:ss" placeholder="请选择时间" />
        </el-form-item>
        <el-form-item label="截止时间" prop="deadline_at">
          <el-date-picker
            v-model="temp.deadline_at"
            type="datetime"
            format="yyyy-MM-dd HH:mm"
            default-time="18:00:00"
            value-format="yyyy-MM-dd HH:mm:ss"
            placeholder="请选择时间"
          />
        </el-form-item>
        <el-form-item label="执行人" prop="execute_by">
          <el-select v-model="temp.execute_by" disabled multiple class="filter-item" placeholder="请选择" @change="$forceUpdate()" />
          <!-- <el-select v-model="temp.execute_by" disabled multiple class="filter-item" :placeholder="uuName" @change="$forceUpdate()" /> -->
        </el-form-item>
        <el-form-item label="创建人" prop="created_by">
          <el-select v-model="temp.created_by" disabled class="filter-item" :placeholder="temp.created_by.nickname" @change="$forceUpdate()" />
        </el-form-item>
        <el-form-item label="优先级" prop="priority">
          <el-select v-model="temp.priority" class="filter-item" placeholder="请选择" @change="$forceUpdate()">
            <el-option v-for="item in priorityOptions" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="状态" prop="status">
          <el-select v-model="temp.status" class="filter-item" placeholder="请选择" @change="handleStatusProgress">
            <el-option v-for="item in statusOptions" :key="item.id" :label="item.name" :value="item.id" />
          </el-select>
        </el-form-item>
        <el-form-item label="进度(%)" prop="progress">
          <el-input-number v-model="temp.progress" controls-position="right" :min="0" :max="100" />
        </el-form-item>
        <el-form-item label="创建时间" prop="created_at">
          <el-date-picker v-model="temp.created_at" disabled type="datetime" format="yyyy-MM-dd HH:mm" default-time="09:00:00" value-format="yyyy-MM-dd HH:mm:ss" placeholder="请选择时间" />
        </el-form-item>
        <el-form-item label="完成时间" prop="complete_at">
          <el-date-picker v-model="temp.complete_at" disabled type="datetime" format="yyyy-MM-dd HH:mm" default-time="09:00:00" value-format="yyyy-MM-dd HH:mm:ss" placeholder="请选择时间" />
        </el-form-item>
        <br>
        <el-form-item label="描述">
          <div ref="introTextarea" class="input-textarea" contenteditable placeholder="请输入" style="width:calc(50vw - 140px)" @paste="handlePaste" />
          <!-- <el-input v-model="temp.intro" :autosize="{ minRows: 2, maxRows: 4}" type="textarea" placeholder="请输入" /> -->
        </el-form-item>
      </el-form>
      <div slot="footer" class="dialog-footer">
        <el-button type="danger" style="float: left;" @click="handleDelete(temp)">
          删除
        </el-button>
        <el-button @click="dialogFormVisible = false">
          取消
        </el-button>
        <el-button type="primary" @click="dialogStatus==='create'?createData():updateData()">
          确认
        </el-button>
      </div>
    </el-dialog>
  </el-card>
</template>

<script>
import { parseTime, resizeImage } from '@/utils'
import * as DefectApi from '@/api/defect'
import ListView from './list'

export default {
  name: 'Defects',
  components: { ListView },
  data() {
    return {
      total: 0,
      loading: false,
      showDone: false,
      listData: [],
      priorityOptions: [
        {
          id: 1,
          name: '非常高'
        },
        {
          id: 2,
          name: '高'
        },
        {
          id: 3,
          name: '一般'
        },
        {
          id: 4,
          name: '低'
        }
      ],
      statusOptions: [
        {
          id: 1,
          name: '未开始'
        },
        {
          id: 2,
          name: '进行中'
        },
        {
          id: 3,
          name: '已完成'
        },
        {
          id: 4,
          name: '取消'
        }
      ],
      temp: {
        name: '',
        intro: '',
        weight: '',
        status: 1,
        progress: 0,
        priority: 3,
        execute_by: [],
        created_by: {},
        start_at: '',
        deadline_at: ''
      },
      dialogFormVisible: false,
      dialogStatus: '',
      textMap: {
        update: '编辑',
        create: '创建'
      },
      rules: {
        name: [{ required: true, message: '必须填写名称', trigger: 'blur' }],
        execute_by: [{ required: true, message: '必须填写执行人', trigger: 'blur' }]
      }
    }
  },
  computed: {
    uuid() {
      return this.$store.state.user.userInfo.id
    },
    uuName() {
      return this.$store.state.user.userInfo.nickname
    }
  },
  mounted() {
    this.getDefectsList()
  },
  methods: {
    handleChangeSwitch() {
      this.getDefectsList()
    },
    async getDefectsList() {
      this.listData = []
      this.total = 0
      this.loading = true
      const { data } = await DefectApi.getDefects({ 'user_id': this.uuid, 'done': (this.showDone && 3) || null })
      if (data && data.total) {
        this.listData = data.items
        this.total = data.total
      }
      this.loading = false
    },
    async updateCheckboxApi(event, row) {
      const temp = {}
      temp['id'] = row.id
      temp['name'] = row.name
      temp['status'] = event ? 3 : 1
      temp['intro'] = row.intro
      temp['priority'] = row.priority
      temp['progress'] = event ? 100 : 0
      // temp['execute_by'] = [this.uuid]
      temp['execute_by'] = (row.execute_by.length && row.execute_by.map(item => { return item.id })) || []
      temp['deadline_at'] = row.deadline_at
      temp['complete_at'] = parseTime(new Date())
      temp['start_at'] = row.start_at
      temp['created_by'] = row.created_by.id
      temp['project_id'] = row.project.id
      const { data } = await DefectApi.updateDefect(temp)
      if (data) {
        await this.getDefectsList()

        await this.$notify({
          title: 'Success',
          message: '更新成功',
          type: 'success',
          duration: 2000
        })
      }
    },
    async handleUpdate(row) {
      this.temp['id'] = row.id
      this.temp['name'] = row.name
      this.temp['status'] = row.status
      this.temp['weight'] = row.weight
      this.temp['intro'] = row.intro
      this.temp['priority'] = row.priority
      this.temp['progress'] = row.progress
      this.temp['created_at'] = row.created_at
      this.temp['complete_at'] = row.complete_at
      // this.temp['execute_by'] = [this.uuName]
      this.temp['execute_by_id'] = (row.execute_by.length && row.execute_by.map(item => { return item.id })) || []
      this.temp['execute_by'] = (row.execute_by.length && row.execute_by.map(item => { return item.nickname })) || []
      this.temp['deadline_at'] = row.deadline_at
      this.temp['start_at'] = row.start_at
      this.temp['created_by'] = row.created_by
      this.temp['project_id'] = row.project
      setTimeout(() => {
        if (this.$refs.introTextarea) {
          this.$refs.introTextarea.innerHTML = row.intro
        }
      }, 0)

      this.dialogStatus = 'update'
      this.dialogFormVisible = true
      this.$nextTick(() => {
        this.$refs['dataForm'].clearValidate()
      })
    },
    validateStartEndTime(temp) {
      if (!temp.start_at || !temp.deadline_at) return true
      // Safari 日期格式处理
      if (/Safari/.test(navigator.userAgent) && !/Chrome/.test(navigator.userAgent)) {
        return new Date(temp.start_at.replaceAll(/-/g, '/')).getTime() < new Date(temp.deadline_at.replaceAll(/-/g, '/')).getTime()
      }
      return new Date(temp.start_at).getTime() < new Date(temp.deadline_at).getTime()
    },
    handleStatusProgress(val) {
      this.$forceUpdate()
      console.log(val)
      switch (val) {
        case 3:
          this.temp['progress'] = 100
          break
        default:
          this.temp['progress'] = 0
          break
      }
    },
    updateData() {
      this.$refs['dataForm'].validate(async(valid) => {
        const timeValid = this.validateStartEndTime(this.temp)
        if (!timeValid) {
          await this.$message.error('截止时间必须大于开始时间！')
          return
        }
        if (valid) {
          // this.temp['execute_by'] = [this.uuid]
          this.temp['execute_by'] = this.temp['execute_by_id']
          this.temp['complete_at'] = (this.temp.status === 3 || this.temp.progress === 100) ? parseTime(new Date()) : null
          this.temp['intro'] = this.$refs.introTextarea.innerHTML

          const { data } = await DefectApi.updateDefect(this.temp)
          if (data) {
            await this.getDefectsList()
            this.dialogFormVisible = false
            await this.$notify({
              title: 'Success',
              message: '更新成功',
              type: 'success',
              duration: 2000
            })
          }
        }
      })
    },
    handleDelete(row, index) {
      this.$confirm('此操作删除该项, 是否继续?', '提示', {
        confirmButtonText: '确定',
        cancelButtonText: '取消',
        type: 'warning'
      }).then(async() => {
        await DefectApi.deleteDefect(row.id)
        await this.getDefectsList()
        this.dialogFormVisible = false

        await this.$notify({
          title: 'Success',
          message: '删除成功！',
          type: 'success',
          duration: 2000
        })
      }).catch(err => {
        console.error(err)
        this.dialogFormVisible = false
        this.$notify({
          title: 'Fail',
          message: '已取消删除',
          type: 'error',
          duration: 2000
        })
      })
    },
    handlePaste(e) {
      const file = e.clipboardData.files[0]
      if (file && file.type.startsWith('image')) {
        e.preventDefault()
        resizeImage(file).then(res => {
          this.$refs.introTextarea.innerHTML += `<img style="max-width: 100%;cursor: pointer" src="${res}" />`
          this.curSorMoveEnd()
        })
      }
    }
  }
}
</script>

<style lang="scss" scoped>
h3 {
  margin: 0;
  padding: 0;
}
.input-textarea {
  display: block;
  width: 100%;
  box-sizing: border-box;
  flex: auto;
  border: 1px solid #ccc;
  border-radius: 5px;
  padding: 0.5rem;
  min-height: 8rem;
  max-height: 12rem;
  line-height: 1.4;
  font-size: 1rem;
  resize: none;
  background: none;
  overflow-x: hidden;
  overflow-y: auto;
}
</style>
